<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Middleware;

use Hyperf\Context\Context;
use Hyperf\HttpMessage\Exception\NotFoundHttpException;
use Hyperf\HttpMessage\Stream\SwooleFileStream;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

use function Hyperf\Config\config;

class StaticMiddleware implements MiddlewareInterface
{
    public function __construct(protected ContainerInterface $container)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 静态资源
        $currUrl = trim($request->getUri()->getPath(), '/');
        $extension = pathinfo($currUrl, PATHINFO_EXTENSION);
        if (! empty($extension) && $extension !== 'php') {
            // 配置文件可看这里：https://www.hyperf.wiki/2.1/#/zh-cn/filesystem?id=%e9%85%8d%e7%bd%ae%e9%9d%99%e6%80%81%e8%b5%84%e6%ba%90
            if (! config('server.settings.enable_static_handler')) {
                throw new NotFoundHttpException();
            }
            // 根据url拼接实际的保存路径
            # $static_file = config('server.settings.document_root').DIRECTORY_SEPARATOR.'upload' . DIRECTORY_SEPARATOR.'static'.DIRECTORY_SEPARATOR . $currUrl;
            $static_file = config('server.settings.document_root') . DIRECTORY_SEPARATOR . $currUrl;
            if (! is_file($static_file)) {
                throw new NotFoundHttpException();
            }
            return Context::get(ResponseInterface::class)
                ->withHeader('Server', 'crashing')
                ->withBody(new SwooleFileStream($static_file));
        }
        return $handler->handle($request);
    }
}
